package com.kchouse.homepage;


import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.kchouse.MainActivity;
import com.kchouse.R;
import com.kchouse.StartActivity;
import com.kchouse.bean.HostItem;
import com.kchouse.common.API;
import com.kchouse.common.BaseFragment;
import com.kchouse.common.MyHttpCycleContext;
import com.kchouse.common.ToastUtils;
import com.kchouse.myadapter.MerchantAdapter;

import java.util.ArrayList;

import cn.finalteam.okhttpfinal.BaseHttpRequestCallback;
import cn.finalteam.okhttpfinal.HttpRequest;
import cn.finalteam.okhttpfinal.RequestParams;
import me.fangx.haorefresh.HaoRecyclerView;
import me.fangx.haorefresh.LoadMoreListener;

/**
 * 商家套餐列表
 */
public class ListProjcetFragment extends BaseFragment {


    private int single;//1/0，1表示单品，0表示套餐
    private String name;
    private String id;
    private LayoutInflater inflater;
    private View view;
    private int page = 1;
    private int totalCount;//总个数

    private ArrayList<HostItem> listmerchant = new ArrayList();
    private HaoRecyclerView hao_recycleview;
    private MerchantAdapter merchantAdapter;
    private View rl_empty;
    private Intent intent=new Intent();

    public ListProjcetFragment() {
        // Required empty public constructor
    }

    @SuppressLint("ValidFragment")//项目id 名称 排序（可不用）
    public ListProjcetFragment(String id, String name, int single) {
        this.id = id;
        this.name = name;
        this.single = single;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {


        if (view == null) {
            this.inflater = inflater;
            view = inflater.inflate(R.layout.fragment_list_projcet, null);
            intiData();
            intiView();
        }

        return view;

    }

    private void intiView() {

        hao_recycleview = (HaoRecyclerView) view.findViewById(R.id.hao_recycleview);
        rl_empty = view.findViewById(R.id.rl_empty);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        hao_recycleview.setLayoutManager(layoutManager);
        merchantAdapter = new MerchantAdapter(getActivity(), listmerchant);
        hao_recycleview.setAdapter(merchantAdapter);

        hao_recycleview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                HostItem item = listmerchant.get(position);
                intent.putExtra("isDir", false);
                intent.putExtra("id", item.getId());
                intent.setClass(getActivity(), GoodsDetailsActivity.class);
                startActivity(intent);
            }
        });
                hao_recycleview.setLoadMoreListener(new LoadMoreListener() {
                    @Override
                    public void onLoadMore() {
                        new Handler().postDelayed(new Runnable() {
                            public void run() {
                                page = page + 1;
                                GetProjectList(single, name, page);
                                hao_recycleview.loadMoreComplete();

                            }
                        }, 2000);
                    }
                });
    }


    private void intiData() {
        GetProjectList(single, name, page);
    }


    /**
     * 商家优惠套餐
     */
    private void GetProjectList(final int single, final String name, int page) {
        String url = API.GetProjectList;
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数
        params.addFormDataPart("single", single);
        params.addFormDataPart("projectType", name);
        params.addFormDataPart("page", page);
        params.addFormDataPart("pageSize", 10);
        params.addFormDataPart("lat", StartActivity.mLatitude+"");
        params.addFormDataPart("log", StartActivity.mLongitude+"");
        params.addFormDataPart("userId", MainActivity.userid);

        HttpRequest.get(url, params, new BaseHttpRequestCallback<String>() {

            //请求网络前
            @Override
            public void onStart() {
                showdialog();
            }

            @Override
            protected void onSuccess(String str) {
                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    totalCount = data.getInteger("totalCount");

                    if (listmerchant.size() == totalCount)//总个数已满
                    {
                        hao_recycleview.setCanloadMore(false);
                        ToastUtils.getInstanc(getActivity()).showToast("暂无更多");
                    } else {
                        listmerchant.addAll(JSONObject.parseArray(data.getString("merchantList"), HostItem.class));
                        merchantAdapter.notifyDataSetChanged();
                    }
                    if(listmerchant.size()==0)
                    {
                        rl_empty.setVisibility(View.VISIBLE);
                    }
                } else {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    ToastUtils.getInstanc(getActivity()).showToast(data.getString("msg"));
                }
            }

            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
//                toast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);
            }

            //请求网络结束
            @Override
            public void onFinish() {
                dismissdialog();
            }
        });
    }


}
